package com.whnk.attendance.threadpool;

import com.whnk.attendance.threadpool.configfile.ThreadPoolConfigProperties;
import com.whnk.attendance.threadpool.ext.ThreadPoolTaskExecutorExt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

@Configuration
@EnableAsync
public class ThreadPoolConfig {

    @Autowired
    private ThreadPoolConfigProperties threadPoolConfigProperties;

    @Bean("back_cron_job")
    public Executor asyncServiceExecutor_mq_producer() throws Exception {
        return getExecutor(getThreadPoolMap("back_cron_job"));
    }


    private Executor getExecutor(ThreadPoolConfigProperties.ThreadPoolVo threadPoolVo) {

        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutorExt();

        // 核心线程数
        executor.setCorePoolSize(threadPoolVo.getCorePoolSize());

        // 最大线程数
        executor.setMaxPoolSize(threadPoolVo.getMaxPoolSize());

        // 线程池中的线程的名称前缀
        executor.setThreadNamePrefix(threadPoolVo.getThreadNamePrefix());

        // rejection-policy：当pool已经达到max size的时候，如何处理新任务
        // CALLER_RUNS：不在新线程中执行任务，而是有调用者所在的线程来执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());

        //执行初始化
        executor.initialize();

        return executor;
    }

    /**
     * 从配置文件中读取线程池配置
     * @return 线程池对象
     * @throws Exception 异常
     */
    private ThreadPoolConfigProperties.ThreadPoolVo getThreadPoolMap(String threadPoolName) {
        List<ThreadPoolConfigProperties.ThreadPoolVo> threadPoolVoList = threadPoolConfigProperties.getPool();
        for (ThreadPoolConfigProperties.ThreadPoolVo threadPoolVo : threadPoolVoList) {
            if (threadPoolName.equals(threadPoolVo.getThreadName())) {
                return threadPoolVo;
            }
        }

        return null;
    }

}
